const { parse } = require("csv-string")
const fs = require("fs");
const { INCLUDE_REPOS_FOR_PRODUCT, EXCLUDE_REPOS_FOR_PRODUCT } = require("../constant");

class MatrixProduct {
    data;
    dataTitles;
    constructor(path) {
        this.path = path
    }
    parse(){
        const csvString = fs.readFileSync(this.path).toString()
        this.data = parse(csvString)
        this.dataTitles = this.data[0]
    }
    match(product, line) {
        const productIndex = this.dataTitles.findIndex(title => title === product)
        return line[productIndex] === "Y"
    }
    matchedRepos(productName) {
        const repos = []
        const productTitle = this.dataTitles.find(title => title.toLocaleLowerCase().includes(productName))
        this.data.slice(1).forEach(lines => {
            if (this.match(productTitle, lines)) {
                repos.push(lines[0])
            }
        });
        return this.missingRepos(productName, repos)
    }
    missingRepos(productName, repos) {
        if (
            INCLUDE_REPOS_FOR_PRODUCT[productName] && 
            INCLUDE_REPOS_FOR_PRODUCT[productName].length
        ) {
            repos = repos.concat(INCLUDE_REPOS_FOR_PRODUCT[productName])
        }
        if (
            EXCLUDE_REPOS_FOR_PRODUCT[productName] && 
            EXCLUDE_REPOS_FOR_PRODUCT[productName].length
        ) {
            repos = repos.filter(repo => !EXCLUDE_REPOS_FOR_PRODUCT[productName].includes(repo))
        }
        return repos
    }
}

MatrixProduct.fromPath = path => {
    const matrixProduct = new MatrixProduct(path)
    matrixProduct.parse()
    return matrixProduct
}

module.exports = MatrixProduct